package unimelb.filesync.client.protocol;

import unimelb.filesync.common.message.NetworkMessage;
import unimelb.filesync.common.message.RequestBlockSizeRole;
import unimelb.filesync.common.message.ResponseBlockSizeRole;
import unimelb.filesync.common.misc.ProtocolContext;
import unimelb.filesync.common.network.NetworkConnection;
import unimelb.filesync.common.network.NetworkService;
import unimelb.filesync.common.protocol.IFileSyncPhase;

public class RequestBlockSizePhase implements IFileSyncPhase {

    private final ProtocolContext context;

    private final NetworkService networkService;

    public RequestBlockSizePhase(ProtocolContext context) {
        super();
        this.context = context;
        this.networkService = new NetworkService();
    }

    @Override
    public void execute() {
        System.out.println("Sending block size role");
        
        final NetworkConnection conn = context.getObject(ProtocolContext.HOT_LINE_CONNECTION);

        final Long blockSize = context.getObject(ProtocolContext.BLOCK_SIZE);
        final String role = context.getObject(ProtocolContext.ROLE);
        final NetworkMessage request = NetworkMessage.createBlockSizeRoleRequestMsg(new RequestBlockSizeRole(blockSize, role));

        networkService.writeMessage(request, conn);
        final NetworkMessage response = networkService.readMessage(conn);
        if (response == null) {
            System.exit(0);
        }
        
        final ResponseBlockSizeRole result = response.getContent();
        if (!result.isSuccess()) {
            throw new RuntimeException("Error:[message=" + result.getErrorMessage() + "]");
        }
    }
}
